<script setup>
import { reactive } from "vue";
import { ref, onMounted } from "vue";
import { defineEmits } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import axios from "axios";
const I18n = useI18n();
const { locale } = useI18n();

const router = useRouter();
const route = useRoute();
// 跳转页面
const jumpTo = (path) => {
  if (typeof changeShowType === "function") {
    changeShowType(false);
  }
  const redirectPath = route.query?.redirect;
  if (typeof redirectPath === "string" && redirectPath) {
    router.replace(redirectPath);
    return;
  }
  if (window.history.length > 1) {
    router.back();
    return;
  }
  router.replace({ path });
};

// 登录表单
const form = reactive({
  account: "",
  password: "",
  agree: false,
});

// 登录函数
const onLogin = async () => {
  if (form.account === "") {
    ElMessage({
      message: "请输入手机号",
      type: "warning",
    });
    return;
  }
  if (form.password === "") {
    ElMessage({
      message: "请输入密码",
      type: "warning",
    });
    return;
  }
  if (form.agree === false) {
    ElMessage({
      message: "请同意用户协议",
      type: "warning",
    });
    return;
  }
  try {
    const res = await axios.post(`${apiUrl}/login`, {
      ...form,
    });

    if (res.data.status === 200) {
      const token = res.data.data.token;
      localStorage.setItem("LOGIN_STATUS_TOKEN", token);
      const info = await getInfo();
      localStorage.setItem("info", JSON.stringify(info));
      ElMessage({
        message: "登录成功",
        type: "success",
      });
      if (info.is_first === 0) {
        changeLoginType("first");
        return;
      } else {
        jumpTo("/person");
      }
    } else {
      ElMessage({
        message: res.data.msg,
        type: "error",
      });
    }
  } catch (e) {}
};

const getInfo = async () => {
  try {
    const res = await axios.get(`${apiUrl}/user`, {
      headers: {
        Authorization: `Bearer ${getToken()}`, // 修正了拼写错误
      },
    });
    return res.data.data; // 返回获取到的数据
  } catch (e) {
    console.error(e); // 打印错误信息
    throw e; // 抛出错误，让调用者可以捕获
  }
};

const emit = defineEmits(["changeLoginType"]);
// 修改登录方式
const changeLoginType = (type) => {
  emit("changeLoginType", type);
};

const showYonghu = ref(false);
const showYinsi = ref(false);
const userXie = ref("");
const yinsiXie = ref("");
const enUserXie = ref("");
const enYinsiXie = ref("");

const getUserXie = async () => {
  try {
    const res = await axios.get(`${apiUrl}/pc/get_news_detail/14`, {
      headers: {
        "Authori-zation": `Bearer ${getToken()}`,
      },
    });

    if (res.data.status === 200) {
      userXie.value = res.data.data.content.replace(/^<p>|<\/p>$/g, "");
    }
  } catch (e) {}
};

const getEnUserXie = async () => {
  try {
    const res = await axios.get(`${apiUrl}/pc/get_news_detail/15`, {
      headers: {
        "Authori-zation": `Bearer ${getToken()}`,
      },
    });

    if (res.data.status === 200) {
      enUserXie.value = res.data.data.content.replace(/^<p>|<\/p>$/g, "");
    }
  } catch (e) {}
};

const getYinsiXie = async () => {
  try {
    const res = await axios.get(`${apiUrl}/pc/get_news_detail/16`, {
      headers: {
        "Authori-zation": `Bearer ${getToken()}`,
      },
    });

    if (res.data.status === 200) {
      yinsiXie.value = res.data.data.content.replace(/^<p>|<\/p>$/g, "");
    }
  } catch (e) {}
};

const getEnYinsiXie = async () => {
  try {
    const res = await axios.get(`${apiUrl}/pc/get_news_detail/16`, {
      headers: {
        "Authori-zation": `Bearer ${getToken()}`,
      },
    });

    if (res.data.status === 200) {
      enYinsiXie.value = res.data.data.content.replace(/^<p>|<\/p>$/g, "");
    }
  } catch (e) {}
};

onMounted(() => {
  getUserXie();
  getEnUserXie();
  getYinsiXie();
  getEnYinsiXie();
});
</script>

<template>
  <div class="loginBox">
    <div class="boxBg">
      <div class="title">{{ $t("loginRegist.logBtn") }}</div>

      <el-form :model="form" label-width="auto">
        <el-form-item label="">
          <el-input
            v-model="form.account"
            :placeholder="$t('loginRegist.placePhone')"
            class="loginInput"
          >
            <template #prepend>+86</template>
          </el-input>
        </el-form-item>
        <el-form-item label="" style="margin-bottom: 5px">
          <el-input
            v-model="form.password"
            :placeholder="$t('loginRegist.placePassword')"
            class="loginInput"
            type="password"
            show-password
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <div class="formItem">
          <el-checkbox v-model="form.agree" size="small">
            <div class="info">
              {{ $t("loginRegist.iagree")
              }}<span class="agreement" @click.stop="showYonghu = true">{{
                $t("loginRegist.userAgreement")
              }}</span
              >{{ $t("loginRegist.and")
              }}<span class="agreement" @click.stop="showYinsi = true">{{
                $t("loginRegist.privacyAgreement")
              }}</span>
            </div>
          </el-checkbox>
        </div>
        <div class="formItem">
          <el-button type="primary" class="loginBtn" @click="onLogin">{{
            $t("loginRegist.logBtn")
          }}</el-button>

          <div class="changeTypeBtn" @click="changeLoginType('quik')">
            {{ $t("loginRegist.quick") }}
          </div>
        </div>
      </el-form>
    </div>
  </div>

  <el-dialog
    v-model="showYonghu"
    :title="$t('loginRegist.userAgreement')"
    width="60%"
    :before-close="handleClose"
  >
    <span v-html="locale === 'zh-cn' ? userXie : enUserXie"></span>
  </el-dialog>

  <el-dialog
    v-model="showYinsi"
    :title="$t('loginRegist.privacyAgreement')"
    width="60%"
    :before-close="handleClose"
  >
    <span v-html="locale === 'zh-cn' ? yinsiXie : enYinsiXie"></span>
  </el-dialog>
</template>

<style scoped lang="scss">
.loginBox {
  display: flex;
  justify-content: end;

  .boxBg {
    width: 400px;
    background-color: #fff;
    padding: 30px 40px;
    border: 1px solid #ccc;
    position: absolute;
    bottom: 200px;

    .title {
      font-size: 20px;
      margin-bottom: 40px;
      // font-weight: bold;
      letter-spacing: 2px;
      text-align: center;
    }

    .loginInput {
      height: 50px;
      border-radius: 0;
      margin-bottom: 5px;
    }

    .code {
      cursor: pointer;
      width: 70px;
      text-align: center;
    }

    .formItem {
      // display: flex;
      font-size: 12px;

      .info {
        line-height: 24px;

        .agreement {
          color: #156197;
        }
      }

      .loginBtn {
        width: 100%;
        height: 40px;
        margin-top: 30px;
      }

      .changeTypeBtn {
        text-align: center;
        font-size: 14px;
        margin-top: 10px;
        cursor: pointer;
      }
    }
  }
}

::v-deep .el-select__wrapper {
  background-color: rgba(0, 0, 0, 0);
  box-shadow: none;
}

::v-deep .el-select__wrapper:hover {
  box-shadow: none;
}

::v-deep .el-select__selected-item {
  color: #fff;
}

.languageFill:not([stroke]) {
  fill: rgb(255, 255, 255);
  position: relative;
  top: 7px;
}

::v-deep .el-input-group__prepend {
  background-color: #fff;
}

::v-deep .el-input-group__append {
  background-color: #fff;
}
</style>
